package com.itheima.filter;

import cn.hutool.core.util.StrUtil;
import com.itheima.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求url
        String url = request.getRequestURL().toString();

        //判断是否是登录请求,是放行
        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }

        //获取令牌
        String token = request.getHeader("token");
        //判断令牌是否存在
        if (StrUtil.isEmpty(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //解析令牌

        try {
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //放行
        filterChain.doFilter(servletRequest, servletResponse);

    }

}
